package com.yanqu.road.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.util.Properties;

public class ConfigHelper {
	private static Logger logger = LogManager.getLogger(ConfigHelper.class.getName());
	private static Properties properties = null;
	private static String mainPath = null;

	public static String getPath(String key) {
		if (properties == null) {
			return null;
		}

		String path = properties.getProperty(key);
		if (path == null || path.trim().length() == 0) {
			return "";
		}

		return path;
	}

	/**
	 * 读取值
	 *
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		if (properties == null) {
			return null;
		}
		return properties.getProperty(key);
	}

	/**
	 * 读取值
	 *
	 * @param key
	 * @return
	 */
	public static int getInt(String key) {
		if (properties == null) {
			return 0;
		}
		String value = properties.getProperty(key);
		if (SplitHelper.isNumeric(value)) {
			return Integer.parseInt(value);
		}
		return 0;
	}

	public static long getLong(String key) {
		if (properties == null) {
			return 0;
		}
		String value = properties.getProperty(key);
		if (SplitHelper.isNumeric(value)) {
			return Long.parseLong(value);
		}
		return 0;
	}

	public static boolean initConfig(String path) {
		if (path == null || path.equals("")) {
			return false;
		}

		if (path.startsWith("/")) {
			mainPath = path.substring(0, path.indexOf("/", 2));
		}

		if (mainPath != null && mainPath.trim().length() > 0) {
			if (!mainPath.startsWith("/")) {
				return false;
			}
		}

		if (properties == null) {
			return loadProperties(path);
		}

		return true;
	}

	private static boolean loadProperties(String path) {
		try {
			properties = new Properties();
			InputStream inputStream = new BufferedInputStream(new FileInputStream(path));
			properties.load(inputStream);
			return true;
		} catch (FileNotFoundException e) {
			logger.error("异常错误",e);
			return false;
		} catch (IOException e) {
			logger.error("异常错误",e);
			return false;
		}
	}


}
